package com.wanqing.community.controller.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.wanqing.community.bean.DepartmentBean;
import com.wanqing.community.bean.UserBean;
import com.wanqing.community.manager.DepartmentManager;
import com.wanqing.community.util.ConditionParse;
import com.wanqing.community.util.KeyConstant;
import com.wanqing.community.util.StringTools;

public class BaseController {
	
	private static Logger log = Logger.getLogger(BaseController.class);
	
	@Resource
	private DepartmentManager departmentManager;
	
	protected void writeJson(HttpServletResponse response,String content){		
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = null; 
		try {
			out = response.getWriter();
			out.print(content);
		} catch (IOException e) {			
			log.error(e.toString());
		}finally{
			out.close();  
		}
	}
	
	protected void writeText(HttpServletResponse response,String content){	
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = null; 
		try {
			out = response.getWriter();
			out.print(content);
		} catch (IOException e) {			
			log.error(e.toString());
		}finally{
			out.close();  
		}
	}
	
	/**
	 * 
	 * <p>Description:调用JS中的回调方法<p>
	 * @author 高刚强
	 * @version 2013-9-12
	 * @modifier 高刚强
	 * @modifiDate 2013-9-12
	 * <p>modifiContent:<p>
	 * @param response
	 * @param callback  回调函数名
	 * @param args
	 */
	protected void writeCallback(HttpServletResponse response,String callback,String ...args){
		response.setContentType("text/html;charset=UTF-8");
		StringBuffer sb = new StringBuffer();
		sb.append("<script>parent.");
		sb.append(callback);		
		if(args.length==0){
			sb.append("()");
		}else{
			StringBuffer temp = new StringBuffer();
			temp.append("(");
			for (String paramter : args) {
				paramter = StringUtils.replace(paramter, "\"", "");
				paramter = StringUtils.replace(paramter, "\n", "");
				paramter = StringUtils.replace(paramter, "\r", "");
				paramter = StringUtils.replace(paramter, "\t", "");
				temp.append("\"").append(paramter).append("\",");
			}
			String str = StringTools.removeLastString(temp.toString(), ",");
			sb.append(str).append(")");
		}		
		sb.append("</script>");		
		PrintWriter out = null; 
		try {
			out = response.getWriter();
			out.print(sb.toString());
		} catch (IOException e) {			
			log.error(e.toString());
		}finally{
			out.close();  
		}			
	}	
	/**
	 * <p>Description:清除缓存信息<p>
	 * @author GangQiangGao
	 * @version 2013-8-5
	 * @modifier GangQiangGao
	 * @modifiDate 2013-8-5
	 * <p>modifiContent:<p>
	 * @param response
	 */
	protected void clearCache(HttpServletResponse response){
		response.addHeader("Cache-Control", "no-cache");
		response.addHeader("Expires", "-1");
	}	
	/**
	 * <p>Description:在线显示PDF文件<p>
	 * @author 高刚强
	 * @version 2013-9-12
	 * @modifier 高刚强
	 * @modifiDate 2013-9-12
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @param relativePath 文件所在的相对地址
	 * @param fileName 文件名
	 */
	protected void showPdf(HttpServletRequest request, HttpServletResponse response,String relativePath,String fileName){
		response.setContentType("application/pdf");
		StringBuffer sb = new StringBuffer();
		sb.append(request.getSession().getServletContext().getRealPath("/"));
		sb.append(File.separator).append(relativePath).append(File.separator).append(fileName);
		String filePath = sb.toString();
		showPdf(request, response, filePath);
	}
	
	/**
	 * <p>Description:在线显示PDF文件<p>
	 * @author 高刚强
	 * @version 2013-9-12
	 * @modifier 高刚强
	 * @modifiDate 2013-9-12
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response	
	 * @param filePath 文件地址及文件名
	 */
	protected void showPdf(HttpServletRequest request, HttpServletResponse response,String filePath){		
		response.setContentType("application/pdf");
		InputStream in = null;
		ServletOutputStream out = null;
		try{			
			response.reset();
			out = response.getOutputStream();
			in = new BufferedInputStream(new FileInputStream(filePath));
			int ch;
			while((ch = in.read())!=-1){
				out.print((char) ch);
			}
		}catch (Exception e) {
			log.error("在线显示PDF文件异常："+e.toString());
		}finally{
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				log.error("在关闭流的时候出现异常："+e.toString());
			}
		}
	}
	
	/**
	 * <p>Description:在线显示图片<p>
	 * @author 高刚强
	 * @version 2013-9-12
	 * @modifier 高刚强
	 * @modifiDate 2013-9-12
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response	
	 * @param filePath 文件地址及文件名
	 */
	protected void showImage(HttpServletRequest request, HttpServletResponse response,String filePath){
		response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		InputStream in = null;
		ServletOutputStream out = null;
		try{			
			response.reset();
			out = response.getOutputStream();
			in = new BufferedInputStream(new FileInputStream(filePath));
			int ch;
			while((ch = in.read())!=-1){
				out.print((char) ch);
			}
		}catch (Exception e) {
			log.error("在线显示图片文件异常："+e.toString());
		}finally{
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				log.error("在关闭流的时候出现异常："+e.toString());
			}
		}
	}
	
	/**
	 * <p>Description:得到post或get传的参数及参数名<p>
	 * @author 高刚强
	 * @version 2013-10-22
	 * @modifier 高刚强
	 * @modifiDate 2013-10-22
	 * <p>modifiContent:<p>
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected Map<String, String> getParameters(HttpServletRequest request){
		Map<String, String[]> map = request.getParameterMap();		//luke Map<String, String> map Map<String, String[]> map
		Set<String> sets = map.keySet();
		Map<String, String> result = null;
		if(null!=sets && !sets.isEmpty()){
			result = new HashMap<String, String>();
			for (String key : sets) {
				if(!"method".equals(key) && !"m_name".equals(key)){
					result.put(key, StringTools.objectToString(request.getParameter(key)));
				}			
			}
		}
		return result;
	}
	
	/**
	 * <p>Description:查询所有的县市<p>
	 * @author 高刚强
	 * @version 2014-7-28
	 * @modifier 高刚强
	 * @modifiDate 2014-7-28
	 * <p>modifiContent:<p>
	 * @return
	 */
	protected List<DepartmentBean> listCitys(){
		ConditionParse condParse = new ConditionParse();
		condParse.addCondition("PID", "=", "000");
		condParse.addWhereStr();
		return this.departmentManager.queryDepartment(condParse);
	}
	
	/**
	 * <p>Description:查询所有的县市<p>
	 * @author 高刚强
	 * @version 2014-7-28
	 * @modifier 高刚强
	 * @modifiDate 2014-7-28
	 * <p>modifiContent:<p>
	 * @return
	 */
	protected DepartmentBean listCitys(String orgName){
		ConditionParse condParse = new ConditionParse();
		condParse.addCondition("ORGNAME", "=", orgName);
		condParse.addWhereStr();
		List<DepartmentBean> list = this.departmentManager.queryDepartment(condParse);
		DepartmentBean depart = null;
		if(null!=list && !list.isEmpty()){
			depart = list.get(0);
		}
		return depart;
	}
	
	protected UserBean getLoginUser(HttpServletRequest request){
		HttpSession session = request.getSession();
		UserBean user = (UserBean) session.getAttribute(KeyConstant.USER_SESSION);
		return user;		
	}
}
